import multipart from '@fastify/multipart';
import { ConstantEnum } from '@libs/common/enums';
import {
  AllExceptionsFilter,
  HttpExceptionFilter,
} from '@libs/common/exceptions';
import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import {
  FastifyAdapter,
  NestFastifyApplication,
} from '@nestjs/platform-fastify';

import { AppModule } from './app.module';
import { generateDocument } from './doc';

declare const module: any;

async function bootstrap() {
  const fastify = new FastifyAdapter({ logger: false });
  const app = await NestFactory.create<NestFastifyApplication>(
    AppModule,
    fastify,
  );

  app.useLogger(app.get(ConstantEnum.WINSTON_LOGGER_TOKEN));

  app.useGlobalPipes(new ValidationPipe({ transform: true }));

  const logger = app.get(ConstantEnum.WINSTON_LOGGER_TOKEN);

  app.useGlobalFilters(
    new AllExceptionsFilter(logger),
    new HttpExceptionFilter(logger),
  );

  app.setGlobalPrefix('service-crm-node');

  // @ts-expect-error 无法识别
  await app.register(multipart);

  app.enableCors();

  generateDocument(app);

  if (module.hot) {
    module.hot.accept();
    module.hot.dispose(() => app.close());
  }

  await app.listen(3000, '0.0.0.0');
  console.log(`Application is running on: ${await app.getUrl()}`);
}
bootstrap();
